package org.amphiprion.montrictracv4.task.ludotheque;

import org.amphiprion.montrictracv4.R;
import org.amphiprion.montrictracv4.db.model.Game;
import org.amphiprion.montrictracv4.db.model.GameExtensionList;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.AsyncTask;

public class SynchronizeExtensionOfGameTask extends
		AsyncTask<Void, Integer, GameExtensionList> {

	private Context context;
	private Game game;
	private ProgressDialog progress;
	private SynchronizeExtensionOfGameListener caller;

	public SynchronizeExtensionOfGameTask(Context context, Game game,
			SynchronizeExtensionOfGameListener caller) {
		this.context = context;
		this.game = game;
		this.caller = caller;
	}

	@Override
	protected GameExtensionList doInBackground(Void... params) {

		WebExtentionOfGameParser parser = new WebExtentionOfGameParser(context,
				game, this);
		return parser.parse();
	}

	@Override
	protected void onPreExecute() {
		progress = ProgressDialog.show(context, game.name,
				context.getString(R.string.list_extensions, 0), true, true,
				new DialogInterface.OnCancelListener() {
					@Override
					public void onCancel(DialogInterface dialog) {
						cancel(true);
						caller.importEnded(false, null);
					}
				});
	}

	public void publishProgress(int gameNumber, int totalGame) {
		publishProgress(R.string.list_extensions_progress, gameNumber,
				totalGame);
	}

	@Override
	protected void onProgressUpdate(Integer... values) {
		progress.setMessage(context.getResources().getString(values[0],
				values[1], values[2]));
	}

	@Override
	protected void onPostExecute(GameExtensionList result) {
		progress.cancel();

		if (!isCancelled()) {
			caller.importEnded(result != null, result);
		}
	}

	public interface SynchronizeExtensionOfGameListener {
		void importEnded(boolean succeed, GameExtensionList result);
	}
}
